/*
 * Copyright (C) 2023 HiHope Open Source Organization .
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 *
 * limitations under the License.
 */

#include <stdio.h>
#include <unistd.h>

#include "ohos_init.h"
#include "cmsis_os2.h"

#include "hi_io.h"
#include "iot_gpio.h"

#include "pzcar_i2c_ctrl.h"

int I2C0Init(void)
{
    // I2C0 inited for all components
    IoTGpioInit(HI_IO_NAME_GPIO_13);
    IoTGpioInit(HI_IO_NAME_GPIO_14);
    hi_io_set_func(HI_IO_NAME_GPIO_13, HI_IO_FUNC_GPIO_13_I2C0_SDA);
    hi_io_set_func(HI_IO_NAME_GPIO_14, HI_IO_FUNC_GPIO_14_I2C0_SCL);

    return IoTI2cInit(I2C0_IDX, I2C0_BAUDRATE);
}

int I2C0DeInit(void)
{
    return IoTI2cDeinit(I2C0_IDX);
}

int I2C0_Write(const unsigned char *data, unsigned int dataLen)
{
    if ((data != NULL) && (dataLen > 0)) {
        #if 0
        if (dataLen == 5) {
            printf("%s: Reg[0x%02X]: 0x%02X%02X 0x%02X%02X\n", __func__,
                data[0], data[1], data[2], data[3], data[4]);
        }
        #endif
        return IoTI2cWrite(I2C0_IDX, PZ_CAR_I2C_ADDR, data, dataLen);
    }
    return -1;
}

int I2C0_Read(unsigned char *data, unsigned int dataLen)
{
    if ((data != NULL) && (dataLen > 0)) {
        return IoTI2cRead(I2C0_IDX, PZ_CAR_I2C_ADDR, data, dataLen);
    }
    return -1;
}
